﻿function AzureOnlineQueueMessageDetailsView(context) {

    var dispatcher = $({});
    var content = ko.observable('');
    var encodeBase64 = ko.observable(true);
    var triedToSubmit = ko.observable(false);

    function reset(encodeAsBase64) {
        triedToSubmit(false);
        content('');
        encodeBase64(!!encodeAsBase64);
    }

    function validate() {
        triedToSubmit(true);
        return true;
    }
    
    function escape(str) {
        return $('<div/>').text(str).html();
    }

    function create() {
        var queueName = context.queues.queue();
        var cnt = content();
        if (encodeBase64()) {
            var utf8 = new UTF8();
            var bytes = utf8.getBytes(cnt);
            cnt = new Base64().encode(bytes);
        }
        var xml = '<QueueMessage>';
        xml += '<MessageText>';
        xml += escape(cnt);
        xml += '</MessageText>';
        xml += '</QueueMessage>';
        if (validate()) {
            var api = context.api();
            api.queues.putMessage({
                queue: queueName,
                content: xml,
                success: function () {
                    reset();
                    dispatcher.trigger('success');
                }
            });
        }
    }

    this.reset = reset;
    this.create = create;
    this.content = content;
    this.encodeBase64 = encodeBase64;

    this.addOnSuccess = function (handler) {
        dispatcher.bind('success', handler);
    };
}